<script setup>
import { ref, computed, onMounted, nextTick, onBeforeUnmount } from 'vue'
import { getVipComment, getVipProblem, queryUserByMobile } from '@/api/jdb'
import useUserStore from '@/stores/modules/user'
import { showFailToast, showSuccessToast } from 'vant'
import { useRouter, useRoute } from 'vue-router'
import faqHeaderImage from '@/assets/images/12.png'

const userStore = useUserStore()
const router = useRouter()
const route = useRoute()

const onClickLeft = () => {
  router.back()
}

const commentList = ref([])
const problemList = ref([])

const studentCommentsScrollRef = ref(null)

const speed = 20
// 状态管理
const translateY = ref(0)
const wrapperHeight = ref(300)
const animationFrame = ref(null)
const lastTime = ref(0)
const studentCommentsList = ref(null)

// 计算可见项（双倍数据用于无缝衔接）
const visibleItems = computed(() => [...commentList.value, ...commentList.value])

// 计算总内容高度
const totalHeight = computed(() => {
  return studentCommentsList.value.clientHeight / 2
})

// 动画逻辑
const animate = (timestamp) => {
  if (!lastTime.value) lastTime.value = timestamp
  const deltaTime = timestamp - lastTime.value

  // 计算位移
  const deltaY = (speed * deltaTime) / 1000
  translateY.value -= deltaY

  // 循环逻辑
  if (Math.abs(translateY.value) >= totalHeight.value) {
    translateY.value += totalHeight.value
  }

  lastTime.value = timestamp
  animationFrame.value = requestAnimationFrame(animate)
}

const startAnimation = () => {
  animationFrame.value = requestAnimationFrame(animate)
}

const stopAnimation = () => {
  cancelAnimationFrame(animationFrame.value)
}

const init = async () => {
  getVipProblem({params: 1, pageSize: 9999}).then(response => {
    problemList.value = response.data.rows
  })

  getVipComment({params: 1, pageSize: 9999}).then(response => {
    commentList.value = response.data.rows
    nextTick(() => {
      startAnimation()
    })
  })
}

// 初始化高度测量
onMounted(() => {
  nextTick(async () => {
    wrapperHeight.value = studentCommentsScrollRef.value.clientHeight
    await init()
  })
})

onBeforeUnmount(() => {
  stopAnimation()
})

const studentMobile = ref('')
const showQueryUserDialog = ref(false)

const queryUserDialogBeforeClose = (action) => {
  if (action === 'confirm') {
    return true
    // return queryUserByMobile({
    //   mobile: studentMobile.value
    // }).then(response => {
    //   queryUserData.value = response.data
    //   showQueryUserResultDialog.value = true
    //   showQueryUserDialog.value = false
    // })
  }
  return true
}

const openMember = () => {
  showQueryUserDialog.value = true
}



const onBridgeReady = () => {
  // console.log(data.payJson, 'data.payJson')
  // {
  //   appId : appId,     //公众号ID，由商户传入
  //       timeStamp :"1395712654",         //时间戳，自1970年以来的秒数
  //     nonceStr :"e61463f8efa94090b1f366cccfbbb444", //随机串
  //     package: "prepay_id=u802345jgfjsdfgsdg888",
  //     signType : "MD5",         //微信签名方式：
  //     paySign : "70EA570631E4BB79628FBCA90534C63FF7FADD89" //微信签名
  // }
  // const appId = `${process.env.VUE_APP_WE_CHAT_APP_ID}`
  let payData = {
    // appId: "wx256a6d2c8df4c1af",
    // timeStamp: "1738996915",
    // nonceStr: "cc6e0692dff741bb8da6d1a452e21908",
    // package: "prepay_id=wx08144155375737defb274db5990b2b0000",
    // signType: "RSA",
    // paySign: "E72WVszk+6EVzGLHlZr7rI3sq0d+tM+hQFWEbmCTs+G9WPwKtOBvCpAxU+K3rJ+muqLdupvsUus0/mtAqqUC87g0fdeZXh/UsO57JnjZwcxZr7wbmKFhIUG/6q2nZAgXajTZhb+Qbn/TRA6oAVI6o9MG/z8e5+/1fW12TwZlpo5q4Wr2zJgSnxY5nbq7lsGgE9ZIzLVqJev59Yq1M8QvDU6NyXOxJRAKXT47YNf5h+9ZDQ2y14ccdw/uISqdyj0f+kg5ng2/d1qjbdy7uY9/Zg8WGiFvGPqIs3ozDexYMWVy54hksfIzw5FlVYYkcmljeFveCpoLVS3zu7rAhsa/EA==",
  }
  // alert(JSON.stringify(payData))
  // console.log(payData, 'payData')
  WeixinJSBridge.invoke('getBrandWCPayRequest', payData, res => {
    // console.log(res, '微信支付回调信息')
    // console.log(res.err_msg, '微信支付结果')
    // console.log(res.err_msg === "get_brand_wcpay_request:ok", '微信支付结果判断')
    if(res.err_msg === "get_brand_wcpay_request:ok" ){
      // 使用以上方式判断前端返回,微信团队郑重提示：
      // res.err_msg将在用户支付成功后返回ok，但并不保证它绝对可靠。
      // 支付成功后跳转计时平台重新登入
      //
      // this.$router.replace({
      //   name: 'PayResult',
      //   query: {
      //     result: 'success',
      //     description: '支付成功'
      //   }
      // })
      showSuccessToast("操作成功")
      // router.replace({
      //   path: '/user-center'
      // })
    } else if (res.err_msg === 'get_brand_wcpay_request:cancel') {
      // data.description = '您已取消支付'
      // data.showError = true
      showFailToast('您已取消支付');
    } else if (res.err_msg === 'get_brand_wcpay_request:fail') {
      // data.description = '网络异常'
      // data.showError = true
      showFailToast('网络异常');
    }
  });
}
const callPay = () => {
  if (typeof WeixinJSBridge == "undefined"){
    if ( document.addEventListener ) {
      document.addEventListener('WeixinJSBridgeReady', onBridgeReady, false)
    } else if (document.attachEvent) {
      document.attachEvent('WeixinJSBridgeReady', onBridgeReady)
      document.attachEvent('onWeixinJSBridgeReady', onBridgeReady)
    }
  }else{
    onBridgeReady()
  }
}

</script>

<template>
  <van-nav-bar title="购买VIP" left-arrow fixed placeholder @click-left="onClickLeft"/>
  <header class="vip-header"></header>
  <section class="student-comments">
    <header></header>
    <footer>
      <div class="student-comments-scroll" ref="studentCommentsScrollRef">
        <div class="student-comments-list" :style="{ transform: `translateY(${translateY}px)` }" ref="studentCommentsList">
          <div class="student-comments-item" v-for="(item, index) in visibleItems" :key="'comment-list' + index">
            <header>
              <van-image class="avatar" round :src="item.image" />
              <div class="info">
                <div>{{item.userName}}</div>
                <div class="vip-tips">vip学员</div>
              </div>
            </header>
            <footer>{{item.conent}}</footer>
          </div>
        </div>
      </div>
    </footer>
  </section>
  <section class="faq">
    <header>
      <van-image :src="faqHeaderImage" class="faq-header-image" />
    </header>
    <footer>
      <div v-for="(item, index) in problemList" :key="'faq-list' + index">
        <header>Q {{item.title}}</header>
        <section><span>A</span> {{item.content}}</section>
      </div>
    </footer>
  </section>
  <van-button @click="openMember" color="#BF934A" block class="open-btn">开通会员</van-button>
<!--  <van-dialog-->
<!--      v-model:show="showQueryUserDialog"-->
<!--      title="请输入学员手机号"-->
<!--      show-cancel-button-->
<!--      :before-close="queryUserDialogBeforeClose"-->
<!--  >-->
  <van-dialog
      v-model:show="showQueryUserDialog"
      show-cancel-button
      :before-close="queryUserDialogBeforeClose"
  >
    <div class="waiting-content">
      该功能正在优化，即将上线
    </div>
<!--    <van-cell-group>-->
<!--      <van-field v-model="studentMobile"></van-field>-->
<!--    </van-cell-group>-->
  </van-dialog>
</template>

<style scoped>
.waiting-content {
  width:100%;
  height: 100px;
  display: flex;
  text-align: center;
  align-items: center;
  justify-content: center;
}
.vip-header {
  width: 100%;
  height: 635px;
  background-image: url('@/assets/images/9.png');
  background-repeat: no-repeat;
  background-position: center center;
  background-size: 100%;
}
.student-comments {
  width: 100%;
}
.student-comments > header{
  width: 100%;
  height: 25px;
  background-image: url('@/assets/images/10.png');
  background-repeat: no-repeat;
  background-position: center center;
  background-size: 100%;
  margin-bottom: 20px;
}
.student-comments > footer {
  height: 300px;
  overflow: hidden;
  position: relative;
}
.student-comments-item {
  width: 80%;
  box-shadow: #666 0 0 10px;
  margin: 20px auto 0;
  transition: all 0.3s;
}
.student-comments-item > header {
  display: flex;
  align-items: center;
  padding: 10px 15px;
}
.student-comments-item > footer {
  font-size: 12px;
  padding: 10px 15px;
  color: rgb(104, 104, 101);
}
.student-comments-scroll {
  height: 100%;
  position: relative;
}
.student-comments-list {
  position: absolute;
  width: 100%;
  will-change: transform;
}
.info {
  margin-left: 15px;
  display: flex;
  flex-direction: column;
  font-size: 14px;
}
.info .vip-tips {
  font-size: 9px;
  color: rgb(209, 118, 13);
}
.avatar {
  width: 30px;
  height: 30px;
}
.faq {
  width: 100%;
}
.faq > header{
  width: 100%;
  height: 24px;
  text-align: center;
  margin:20px auto;
}
.faq-header-image {
  height: 24px;
  width: 101px;
}
.faq footer {
  width: 80%;
  margin: 0 auto;
}
.faq footer header {
  font-weight: bold;
  text-align: left;
  font-size: 16px;
}
.faq footer section {
  font-size: 14px;
}
.faq footer section span {
  color:  rgb(209, 118, 13);
  font-weight: bold;
}
.faq footer div {
  margin-bottom: 20px;
}
.open-btn {
  width: 80%;
  margin: 0 auto 20px;
}
</style>
